<template>
  <div :style="bottomStaySpace()" class="wrap">
    <div class="form">
      <LabelAndValue :box-style="labelValueStyle" colon label="姓名" label-width="210">
        <Input v-model:value="form.name" disabled placeholder="请输入姓名" />
      </LabelAndValue>
      <LabelAndValue :box-style="labelValueStyle" colon label="手机号" label-width="210">
        <Input v-model:value="form.mobile" disabled maxlength="11" placeholder="请输入手机号" />
      </LabelAndValue>
      <LabelAndValue :box-style="labelValueStyle" colon label="跟进方式" label-width="210" required>
        <div class="select flex_sb_cen" @tap="followWayRef.change()">
          <span v-if="form1.wayName">{{ form1.wayName }}</span>
          <span v-else style="color: rgba(0, 0, 0, 0.25);">请选择跟进方式</span>
          <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
        </div>
      </LabelAndValue>
      <LabelAndValue :box-style="labelValueStyle" colon label="服务类型" label-width="210" required>
        <div class="select flex_sb_cen" @tap="openServiceTypeFn">
          <div v-if="form1.serviceTypeName?.length > 0" class="textLineHidden" style="width: 400rpx">
            <span v-for="(typeName, index) in form1.serviceTypeName" :key="index">{{ typeName }}{{ index < form1.serviceTypeName?.length - 1 ? ' | ' : '' }}</span>
          </div>
          <span v-else style="color: rgba(0, 0, 0, 0.25);">请选择服务类型</span>
          <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
        </div>
      </LabelAndValue>
      <LabelAndValue :box-style="labelValueStyle" colon label="服务时间" label-width="210" required>
        <div class="select flex_sb_cen" @tap="showServiceTime = true">
          <span v-if="form.serviceTime">{{ form.serviceTime }}</span>
          <span v-else style="color: rgba(0, 0, 0, 0.25);">请选择服务时间</span>
          <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
        </div>
      </LabelAndValue>
      <LabelAndValue :box-style="labelValueStyle" colon label="服务地点" label-width="210" required>
        <div class="select flex_sb_cen" @tap="serviceAddressRef.change()">
          <span v-if="form1.serviceAddress">{{ form1.serviceAddress }}</span>
          <span v-else style="color: rgba(0, 0, 0, 0.25);">请选择服务地点</span>
          <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
        </div>
      </LabelAndValue>
      <LabelAndValue :box-style="labelValueStyle" colon label="服务记录" label-width="210" required>
        <div class="select flex_sb_cen" @tap="serviceRecordRef.change()">
          <div v-if="form.content" class="textLineHidden" style="width: 400rpx">{{ form.content }}</div>
          <div v-else style="color: rgba(0, 0, 0, 0.25);">请输入服务记录</div>
          <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
        </div>
      </LabelAndValue>
      <div class="mt26">
        <LabelAndValue colon label="图片上传" label-width="320" required />
        <div class="uploadTip">(最多10个文件 单个最大50M）</div>
        <div class="mt26">
          <Upload :default-file="form.attachment" limit-count="10" limit-size="50" multiple update @file="form.attachment = $event" />
        </div>
      </div>
    </div>
    <div :style="keepBottomSafeDis()" class="suction_bottom_btn">
      <Button :disabled="!canSubmit" size="L" @confirm="submitFn">提交</Button>
    </div>
    <!--  提交成功  -->
    <Popup ref="submitSuccessRef">
      <Pconfirm :is-two-btn="false" confirm-text="返回" @confirm="confirmFn">
        <template #tip>
          <Image name="submit_success" oss size="112" type="png" />
          <div class="submit_tip mt26">提交成功</div>
        </template>
      </Pconfirm>
    </Popup>
    <!-- 跟进方式 -->
    <Drawer ref="followWayRef">
      <div class="popup_box">
        <div class="popup_title">
          <div>请选择跟进方式</div>
          <div class="icon_close" @tap="followWayRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div class="popup_body">
          <div v-for="(item, index) in followWayOptions" :key="index" class="way_item flex_sb_cen" @tap="selectFollowWayFn(item.id, item.text)">
            <div>{{ item.text }}</div>
            <div v-if="followWayId === item.id">
              <Icon height="31" name="icon-dui-blue" width="44" />
            </div>
          </div>
        </div>
        <div :style="keepBottomSafeDis()" class="flex_cen_cen mt20">
          <div class="btn_primary" style="width: 686rpx" @tap="confirmFollowWayFn">确定</div>
        </div>
      </div>
    </Drawer>
    <!--  服务时间  -->
    <up-datetime-picker
      ref="datetimePickerRef"
      v-model="form1.serviceTime1"
      :formatter="formatter"
      :show="showServiceTime"
      has-input
      mode="datetime"
      @cancel="showServiceTime = false"
      @confirm="confirmServiceTimeFn"
    />
    <!-- 服务类型 -->
    <Drawer ref="serviceTypeRef">
      <div class="popup_box">
        <div class="popup_title">
          <div>请选择服务类型-{{ form1.wayName }}</div>
          <div class="icon_close" @tap="serviceTypeRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div class="popup_body">
          <div v-for="(item, index) in serviceTypeOptions" :key="index" class="way_item flex_sb_cen" @tap="selectServiceTypeFn(item.id, item.text)">
            <div>{{ item.text }}</div>
            <div v-if="selectId.indexOf(item.id) !== -1">
              <Icon height="31" name="icon-dui-blue" width="44" />
            </div>
          </div>
        </div>
        <div :style="keepBottomSafeDis()" class="flex_cen_cen mt20">
          <div class="btn_primary" style="width: 686rpx" @tap="confirmServiceTypeFn">确定</div>
        </div>
      </div>
    </Drawer>
    <!--  服务地点  -->
    <Drawer ref="serviceAddressRef" mask>
      <SiteSelect @cancel="serviceAddressRef.change()" @value="setSite" />
    </Drawer>
    <!-- 服务记录 -->
    <Drawer ref="serviceRecordRef">
      <div class="popup_box">
        <div class="popup_title">
          <div>服务记录</div>
          <div class="icon_close" @tap="serviceRecordRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div class="mt16  popup_body">
          <up-textarea v-model="form1.serviceRecord" count height="100" maxlength="500" placeholder="请输入服务记录" />
        </div>
        <div :style="keepBottomSafeDis()" class="mt26 flex_cen_cen">
          <Button size="L" @tap="confirmServiceRecordFn">确定</Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>
<script lang="ts" setup>
import LabelAndValue from '@C/LabelAndValue.vue'
import Input from '@C/Input.vue'
import { reactive, ref, computed } from 'vue'
import Icon from '@C/Icon.vue'
import Upload from '@C/Upload.vue'
import { bottomStaySpace, keepBottomSafeDis, onLoad, onReady, Router, debouncePro } from '@U/common'
import Button from '@C/Button.vue'
import Drawer from '@C/Drawer.vue'
import SiteSelect from '@C/SiteSelect.vue'
import Popup from '@C/Popup.vue'
import Pconfirm from '@C/Pconfirm.vue'
import Image from '@C/Image.vue'
import { Msg } from '@C/Msg'
import dayjs from 'dayjs'
import { IObj } from '@/interface'
import { addFollowRecords, getFollowWayList, getServiceTypeList, updateFollowRecords } from './request'

let wayText = ''
onLoad((option: any) => {
  wayText = option.wayText
  // 新增
  if (option.wayText === 'add') {
    const { name, mobile, id } = JSON.parse(option.customerInfo)
    form.customerId = id
    form.name = name
    form.mobile = mobile
  }
  // 修改
  if (option.wayText === 'update') {
    const followInfo = JSON.parse(option.followInfo)
    for (const key in form) {
      form[key] = followInfo[key] || ''
    }
    followWayId.value = followInfo.wayId
    selectId.value = followInfo.wayDetailId
    form1.wayName = followInfo.wayName
    form1.serviceTime1 = followInfo.serviceTime
    form1.serviceTypeName = followInfo.wayDetailName
    serviceTypeName1 = JSON.parse(JSON.stringify(followInfo.wayDetailName))
    form1.serviceAddress = `${followInfo.province}/${followInfo.city}/${followInfo.district}`
    form1.serviceRecord = followInfo.content
    getServiceTypeListFn()
  }
})
// 组件样式
const labelValueStyle = { borderBottom: '1rpx solid rgba(0,0,0,0.1)', height: '86rpx', marginTop: '40rpx', paddingRight: 0 }
const form = reactive({
  id: '',
  customerId: '',
  name: '',
  mobile: '',
  wayId: '',
  wayDetailId: [0],
  serviceTime: '',
  province: '',
  provinceCode: '',
  city: '',
  cityCode: '',
  district: '',
  districtCode: '',
  content: '',
  attachment: [],
})
const form1 = reactive({
  wayName: '',
  serviceTime1: Date.now(),
  serviceTypeName: [] as string [],
  serviceAddress: '',
  serviceRecord: '',
})

const followWayRef = ref()
const followWayOptions = ref([])
// 获取跟进方式列表
const getFollowWayListFn = async () => {
  const { code, data } = await getFollowWayList().finally(() => {})
  if (code === 200) {
    followWayOptions.value = data
  }
}
getFollowWayListFn()
const followWayId = ref('')
let wayName = ''
const selectFollowWayFn = (id: string, text: string) => {
  followWayId.value = id
  wayName = text
}
const confirmFollowWayFn = () => {
  form.wayId = followWayId.value
  if (form.wayId === '') return Msg({ msg: '请先选择跟进方式' })
  form1.wayName = wayName
  followWayRef.value.change()
  // 每次选完初始化服务类型
  form1.serviceTypeName = []
  form.wayDetailId = []
  serviceTypeName1 = []
  selectId.value = []
  getServiceTypeListFn()
}
const submitSuccessRef = ref()
const showServiceTime = ref(false)
const datetimePickerRef = ref()
const formatter = (type: string, value: number) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}
onReady(() => {
  // 微信小程序需要用此写法
  datetimePickerRef.value.setFormatter(formatter)
})
const openServiceTypeFn = () => {
  if (!form.wayId) return Msg({ msg: '请先选择跟进方式' })
  serviceTypeRef.value.change()
}
const confirmServiceTimeFn = (timeInfo: object) => {
  form.serviceTime = dayjs(timeInfo.value).format('YYYY-MM-DD HH:mm')
  showServiceTime.value = false
}
// 获取跟进方式对应的服务类型列表
const getServiceTypeListFn = async () => {
  const { code, data } = await getServiceTypeList({ wayId: form.wayId }).finally(() => {})
  if (code === 200) {
    serviceTypeOptions.value = data
  }
}

const serviceTypeRef = ref()
const serviceTypeOptions = ref([])
const selectId = ref([0])
let serviceTypeName1: string [] = []
const selectServiceTypeFn = (id: number, text: string) => {
  if (selectId.value.indexOf(id) === -1) {
    if (selectId.value.length < 3) {
      serviceTypeName1.push(text)
      selectId.value.push(id)
    }
  } else {
    serviceTypeName1 = serviceTypeName1.filter(item => item !== text)
    selectId.value = selectId.value.filter(item => item !== id)
  }
}
const confirmServiceTypeFn = () => {
  form.wayDetailId = selectId.value
  if (form.wayDetailId.length < 1) return Msg({ msg: '请先选择服务类型' })
  form1.serviceTypeName = serviceTypeName1
  serviceTypeRef.value.change()
}
const serviceAddressRef = ref()
const setSite = (e: IObj) => {
  form.province = e?.province.name
  form.city = e?.city.name
  form.district = e?.district.name
  form.provinceCode = e?.province.code
  form.cityCode = e?.city.code
  form.districtCode = e?.district.code
  form1.serviceAddress = `${form.province}/${form.city}/${form.district}`
  serviceAddressRef.value.change()
}
const serviceRecordRef = ref()
const confirmServiceRecordFn = () => {
  if (!form1.serviceRecord) return Msg({ msg: '请先输入服务记录' })
  form.content = form1.serviceRecord
  serviceRecordRef.value.change()
}
const canSubmit = computed(() => (
      form.wayId
      && form.serviceTime
      && form.wayDetailId?.length > 0
      && form.provinceCode
      && form.content
      && form.attachment?.length > 0
))
const submitFn = debouncePro(() => innerSubmit(), 1000)
const innerSubmit = async () => {
  if (!canSubmit.value) return
  let res = {}
  if (wayText === 'add') res = await addFollowRecords(form).finally(() => {})
  if (wayText === 'update') res = await updateFollowRecords(form).finally(() => {})
  if (res.code === 200) {
    submitSuccessRef.value.change()
  }
}
const confirmFn = () => {
  if (wayText === 'add') Router.redirect('declaration_details') // 新增跟进记录后，报单详情页需要重新加载，否则步骤条错乱，所以使用Router.redirect跳转
  if (wayText === 'update') Router.back(2)
  submitSuccessRef.value.change()
}
</script>
<style lang="less" scoped>
.wrap {
  background-color: #fff;
  .form {
    padding: 0 60rpx;
    .select {
      font-size: 28rpx;
      line-height: 86rpx;
    }
  }
  .popup_box {
    .way_item {
      font-weight: 400;
      font-size: 32rpx;
      color: rgba(0,0,0,0.85);
      line-height: 34rpx;
      padding-bottom: 34rpx;
      border-bottom: 2rpx solid #E5E5E5;
      margin-top: 30rpx;
    }
    /deep/ .u-textarea {
      background-color: #F5F6F7;
    }
  }
  /deep/ .one_btn {
    width: 320rpx !important;
  }
  .submit_tip {
    font-weight: 600;
    font-size: 36rpx;
    color: #262626;
    line-height: 50rpx;
  }
  ///deep/ .u-picker__view__column__item {
  //  color: #1890FF;
  //}
}
</style>
